<template>
	<view class="content">
		<view class="good_info">
			<view class="title bef">商品详情</view>
			<view class="inp">
				<view class="label">商品名称：</view>
				<input class="input" type="text" v-model="data.title" placeholder="请输入商品名称" />
			</view>
			<view class="inp">
				<view class="label">商品价格：</view>
				<input class="input" type="digit" v-model="data.price" placeholder="请输入商品价格" />
			</view>
			<view class="inp">
				<view class="label">销售价格：</view>
				<input class="input" type="digit" v-model="data.salePrice" placeholder="请输入销售价格" />
			</view>
			<view class="inp">
				<view class="label">成本价格：</view>
				<input class="input" type="digit" v-model="data.costPrice" placeholder="请输入商品成本价格" />
			</view>
			<view class="inp">
				<view class="label">商品描述：</view>
				<input class="input" type="text" placeholder="请输入商品描述" />
			</view>
		</view>
		<view class="good_type">
			<view class="title bef">商品分类</view>
			<view class="radio">
				<view v-for="(item, index) in data.typelist" :key="index" @click="seltype(item.id)" :class="data.catId === item.id ? 'sel_radio_item' : 'radio_item'">
					{{ item.name }}
				</view>
			</view>
		</view>
		<view class="good_type">
			<view class="title bef">商品类型</view>
			<view class="radio">
				<view v-for="(item, index) in goodsType" :key="index" @click="selGoodType(item.type)" :class="data.type === item.type ? 'sel_radio_item' : 'radio_item'">
					{{ item.name }}
				</view>
			</view>
		</view>
		<view class="good_type" v-if="data.type === 'SET'">
			<view class="title bef">
				<view>套餐商品</view>
				<view style="margin-left: auto" @click="addSETGood">添加商品</view>
			</view>
			<view class="Good_list">
				<view class="Good_item" v-for="(item, index) in data.goodsList" :key="index">
					<view>{{ item.title }}*{{ item.count }}件</view>
				</view>
			</view>
		</view>
		<view class="good_remark">
			<view class="title bef">商品备注</view>
			<textarea v-model="data.remark" placeholder="请输入商品备注" />
		</view>
		<view class="good_img">
			<view class="title bef">商品图片</view>
			<view class="goodimg">
				<image class="img_item" src="../../static/add.png" mode="" @click="upload" />
				<view class="img_item" v-for="(item, index) in data.coverUrl" :key="index">
					<image class="i_guan" src="../../static/guan.png" @click="delimg(index)" />
					<image class="goodimage" :src="item" mode="aspectFit" />
				</view>
			</view>
		</view>
		<view class="but" @click="postgood" v-if="data.id === ''">新增</view>
		<view class="but" @click="postPut" v-else>修改</view>
	</view>
	<canvas
		type="2d"
		id="myCanvas"
		canvas-id="myCanvas"
		:style="{ width: 'data.cWidth' + 'px', height: 'data.cHeight' + 'px' }"
		style="position: absolute; left: -1000px; top: -1000px"
	></canvas>
	<wd-popup v-model="show" position="bottom" custom-style="min-height: 400rpx;" @close="handleClose">
		<view class="PopList">
			<view v-for="(item, index) in Goodlist" :key="index">
				<view :class="item.sel ? 'sel_radio_item' : 'radio_item'" v-if="item.type !== 'SET'">
					<view @click="selGood(index)">
						{{ item.title }}
					</view>
					<view>
						<wd-input-number v-model="item.count" :disabled="!item.sel" />
					</view>
				</view>
			</view>
		</view>
	</wd-popup>
</template>
<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { err, back, toast, get } from '@/utils/uniapi';
import { api } from '@/api/mop_api';
const data = reactive({
	typelist: [],
	catId: '',
	costPrice: '',
	price: '',
	salePrice: '',
	title: '',
	remark: '',
	coverUrl: [],
	id: '',
	page: 1,
	size: 30,
	item: {},
	mchId: '',
	cWidth: '',
	cHeight: '',
	type: 'SIMPLE',
	goodsList: [] as any
});
const show = ref<boolean>(false);
const Goodlist = ref<any>([]);
const goodsType = reactive([
	{ type: 'SIMPLE', name: '普通商品' },
	{ type: 'SET', name: '套餐' }
]);
function handleClose() {
	show.value = false;
	const list = Goodlist.value.filter((e: any) => {
		return e.sel === true;
	});
	data.goodsList = list;
}
function addSETGood() {
	show.value = true;
}
onLoad((e: any) => {
	if (e.id) {
		data.id = e.id;
	}
});
onShow(async () => {
	if (data.id) {
		await getId(data.id);
	}
	Promise.all([getType(), getGoodlist()]);
	data.mchId = get('mchId');
});
async function getId(id: any) {
	try {
		const { respCode, source, msg }: any = await api.goodGet({ id });
		if (respCode === 200) {
			console.log(JSON.parse(source));
			let { title, catId, costPrice, price, salePrice, remark, coverUrl, id, goodsList, type } = JSON.parse(source);
			coverUrl = JSON.parse(coverUrl);
			data.title = title;
			data.catId = catId;
			data.costPrice = costPrice;
			data.price = price;
			data.salePrice = salePrice;
			data.remark = remark;
			data.coverUrl = coverUrl;
			data.id = id;
			data.goodsList = goodsList;
			data.type = type;
		} else {
			toast(msg);
		}
	} catch (error) {
		err(error);
		throw error;
	}
}
async function getGoodlist() {
	try {
		const res: any = await api.goodList({ page: 1, size: 100, data: undefined });
		if (res.respCode === 200) {
			const list = JSON.parse(res.source).map((e: any) => ({
				...e,
				sel: false,
				count: 0
			}));
			Goodlist.value = list;
			if (data.goodsList.length !== 0) {
				list.forEach((e: any) => {
					data.goodsList.forEach((v: any) => {
						if (e.id == v.id) {
							e.sel = true;
							e.count = v.count;
						}
					});
				});
			}
		}
	} catch (e) {
		err(e);
	}
}
function selGood(i: any) {
	const arr = Goodlist.value;
	arr[i].sel = !arr[i].sel;
}
async function getType() {
	const { page, size } = data;
	try {
		const { respCode, source, msg }: any = await api.typelist({ page, size });
		if (respCode === 200) {
			const typelist = JSON.parse(source);
			data.typelist = typelist;
		} else {
			toast(msg);
		}
	} catch (error) {
		err(error);
		throw error;
	}
}
async function postgood() {
	let { title, catId, costPrice, price, salePrice, remark, coverUrl, mchId, type, goodsList } = data;
	const coverUrls = JSON.stringify(coverUrl);
	const lists = goodsList.map((e: any) => ({ id: e.id, count: e.count }));
	const datas = {
		title,
		catId,
		costPrice,
		price,
		salePrice,
		remark,
		coverUrl: coverUrls,
		mchId,
		type,
		goodsList: type === 'SET' ? lists : []
	};
	if (title === '') {
		toast('请输入菜品名称');
	} else if (catId === '') {
		toast('请选择菜品类型');
	} else if (costPrice === '') {
		toast('请输入菜品成本');
	} else if (price === '') {
		toast('请输入菜品价格');
	} else if (salePrice === '') {
		toast('请输入菜品销售价格');
	} else {
		try {
			const res: any = await api.goodpost(datas);
			if (res.respCode === 200) {
				toast('添加成功');
				back();
			} else {
				toast(res.msg);
			}
		} catch (error) {
			err(error);
			throw error;
		}
	}
}
async function postPut() {
	const { title, catId, costPrice, price, salePrice, remark, coverUrl, type, id, mchId, goodsList } = data;
	const coverUrls = JSON.stringify(coverUrl);
	const lists = goodsList.map((e: any) => ({ id: e.id, count: e.count }));
	const datas = {
		title,
		catId,
		costPrice,
		price,
		salePrice,
		remark,
		coverUrl: coverUrls,
		mchId,
		id,
		goodsList: type === 'SET' ? lists : []
	};
	if (title === '') {
		toast('请输入菜品名称');
	} else if (catId === '') {
		toast('请选择菜品类型');
	} else if (costPrice === '') {
		toast('请输入菜品成本');
	} else if (price === '') {
		toast('请输入菜品价格');
	} else if (salePrice === '') {
		toast('请输入菜品销售价格');
	} else {
		try {
			const res: any = await api.goodPut(datas);
			if (res.respCode === 200) {
				back();
				toast('修改成功');
			} else {
				toast(res.msg);
			}
		} catch (error) {
			err(error);
			throw error;
		}
	}
}
function seltype(e: any) {
	data.catId = e;
}
function selGoodType(e: any) {
	data.type = e;
}
function upload() {
	wx.showLoading({ title: '上传中' });
	wx.chooseMedia({
		count: 1,
		mediaType: ['image'],
		sourceType: ['album', 'camera'],
		success: (res) => {
			const head = res.tempFiles[0].tempFilePath;
			compress_img(head);
		},
		fail: () => {
			toast('上传失败');
			wx.hideLoading();
		}
	});
}
function compress_img(img_src: any) {
	let timestamp = new Date().valueOf();
	const query = wx.createSelectorQuery();
	query
		.select('#myCanvas')
		.fields({ node: true, size: true })
		.exec((res) => {
			const canvas = res[0].node;
			const ctx = canvas.getContext('2d');
			let img = canvas.createImage();
			img.src = img_src;
			img.onload = () => {
				let stylewidth = img.width;
				let styleheight = img.height;
				let sizelimit = 200;
				if (Math.max(stylewidth, styleheight) > sizelimit) {
					let percent = sizelimit / Math.max(stylewidth, styleheight);
					stylewidth = Math.trunc(stylewidth * percent);
					styleheight = Math.trunc(styleheight * percent);
				}
				canvas.width = stylewidth;
				canvas.height = styleheight;
				data.cHeight = styleheight;
				data.cWidth = stylewidth;
				ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
				wx.canvasToTempFilePath({
					canvas: canvas,
					fileType: 'jpg',
					quality: 1,
					success: (res) => {
						const { envVersion } = wx.getAccountInfoSync().miniProgram;
						let baseUrl: any = '';
						if (envVersion === 'release') {
							baseUrl = 'https://prod-ymk-order.ymk.vin/order/upload';
						} else {
							baseUrl = 'https://dev-ymk-order.ymk.vin/order/upload';
						}
						uni.uploadFile({
							url: baseUrl,
							filePath: res.tempFilePath,
							name: 'file',
							success: (res) => {
								const data = JSON.parse(res.data);
								toast(data.message);
								let { coverUrl } = data;
								const imgUrl = JSON.parse(data.data.item).filePath;
								coverUrl.unshift(imgUrl);
								data.coverUrl = coverUrl;
							},
							fail: (err) => {
								console.log(err);
								toast('上传失败');
							}
						});
					}
				});
			};
		});
}
function delimg(e: any) {
	let { coverUrl } = data;
	coverUrl.splice(e, 1);
	data.coverUrl = coverUrl;
}
</script>

<style scoped lang="scss">
.good_img {
	width: 710rpx;
	min-height: 338rpx;
	background: #ffffff;
	border-radius: 24rpx 24rpx 24rpx 24rpx;
	margin: 22rpx auto;
	padding: 28rpx;
	box-sizing: border-box;
}
.title {
	display: flex;
	border-bottom: 2rpx solid #ebebf0;
}
.goodimage {
	width: 200rpx;
	height: 200rpx;
}
.goodimg {
	overflow: hidden;
}
.img_item {
	width: 200rpx;
	height: 200rpx;
	margin-top: 28rpx;
	margin-left: 12rpx;
	position: relative;
	float: left;
}
.i_guan {
	width: 30rpx;
	height: 30rpx;
	position: absolute;
	top: -10rpx;
	right: -10rpx;
}
.good_info {
	width: 710rpx;
	min-height: 336rpx;
	background: #ffffff;
	border-radius: 24rpx 24rpx 24rpx 24rpx;
	margin: 0 auto;
	padding: 28rpx;
	box-sizing: border-box;
}
.inp {
	overflow: hidden;
	margin-top: 22rpx;
}
.label {
	font-size: 24rpx;
	font-family: Source Han Sans CN-Regular, Source Han Sans CN;
	font-weight: 400;
	color: #999999;
	float: left;
	line-height: 54rpx;
}
.input {
	width: 478rpx;
	height: 54rpx;
	border-radius: 8rpx 8rpx 8rpx 8rpx;
	opacity: 1;
	border: 2rpx solid #d8d8d8;
	font-size: 24rpx;
	font-family: Source Han Sans CN-Regular, Source Han Sans CN;
	font-weight: 400;
	color: #333333;
	padding-left: 16rpx;
	box-sizing: border-box;
}
.but {
	width: 640rpx;
	height: 80rpx;
	background: #e30514;
	border-radius: 48rpx 48rpx 48rpx 48rpx;
	opacity: 1;
	margin: 0 auto;
	margin-top: 90rpx;
	text-align: center;
	line-height: 80rpx;
	font-size: 40rpx;
	font-family: Source Han Sans CN-Regular, Source Han Sans CN;
	font-weight: 400;
	color: #ffffff;
}
.good_type {
	width: 710rpx;
	min-height: 168rpx;
	background: #ffffff;
	border-radius: 24rpx 24rpx 24rpx 24rpx;
	margin: 10rpx auto;
	padding: 28rpx;
	box-sizing: border-box;
}
.radio {
	display: flex;
	flex-wrap: wrap;
}
.radio_item {
	margin: 10rpx;
	min-width: 140rpx;
	min-height: 54rpx;
	border-radius: 8rpx 8rpx 8rpx 8rpx;
	border: 2rpx solid #d8d8d8;
	box-sizing: border-box;
	text-align: center;
	line-height: 54rpx;
	font-size: 24rpx;
	font-family: Source Han Sans CN-Regular, Source Han Sans CN;
	font-weight: 400;
	color: #333333;
}
.sel_radio_item {
	margin: 10rpx;
	min-width: 140rpx;
	height: 54rpx;
	border-radius: 8rpx 8rpx 8rpx 8rpx;
	background: #e30514;
	text-align: center;
	line-height: 54rpx;
	font-size: 24rpx;
	font-family: Source Han Sans CN-Regular, Source Han Sans CN;
	font-weight: 400;
	color: #fff;
}
.good_remark {
	width: 710rpx;
	min-height: 168rpx;
	background: #ffffff;
	border-radius: 24rpx;
	margin: 10rpx auto;
	padding: 28rpx;
	box-sizing: border-box;
}
.good_remark textarea {
	width: 100%;
	height: 100rpx;
}
.Good_list {
	width: 100%;
	display: flex;
	margin-top: 10rpx;
	flex-wrap: wrap;
	.Good_item {
		text-align: center;
		margin-right: 20rpx;
	}
}
.PopList {
	display: flex;
	flex-wrap: wrap;
}
</style>
